<script setup lang="ts">
import {UploadFilled} from "@element-plus/icons-vue";
import type {UploadUserFile} from "element-plus";
import { useMessage } from '@/hooks/web/useMessage'
import {useUploadToWebDisk} from "@/views/ai/webdisk/upload";
import {WebDiskFileApi} from "@/api/ai/webdiskfile";
import { ref, inject } from 'vue';
import {DefSupportedFileTypes} from "@/components/AFile/data";

const props = defineProps({
  dirId:String,
  spaceId:String,
  maxFileSize:{
    type:Number,
    default:500,
  },
  fileTypes:{
    type:Array as PropType<string[]>,
    default:DefSupportedFileTypes,
  },
  modelValue:{
    type:[String,Array],
  },
  checkFile:{
    type:Boolean,
    default:true
  },
  limit:{
    type:Number,
    default:1
  },
  onAfterUpload:{
    type:Function as PropType<(form:any,value:any)=>void>,
    default:undefined
  },
  form:{
    type:Object,
  }
});
// 提供默认值'0'防止useFlow为undefined
const useFlow = inject<string | undefined>('useFlow', '0');
const emits = defineEmits<{
  (e:'update:modelValue',url:string|string[]):void,
}>();
const fileList=reactive<UploadUserFile[]>([])
const urls=reactive<string[]>([])
const message = useMessage() // 消息弹窗
const { uploadUrl, httpRequest } = useUploadToWebDisk( (url:string,type:string,name:string)=>{
  urls.push(url);
  if (props.limit>1){
    emits('update:modelValue',urls)
  }else {
    emits('update:modelValue',url)
  }
  if (props.onAfterUpload&&props.form){
    props?.onAfterUpload(props.form,name)
  }
})
const onUploadError = (err: Error) => message.error('上传失败: ' + err.message)

const uploadingCount=ref(0)
// 支持的文件类型和大小限制
const allowedExtensions = computed(()=>{
  return  props.fileTypes.map((ext) => ext.toLowerCase())
}) // 小写的扩展名列表
const beforeUpload = (file: any) => {
  // 1.1 检查文件扩展名 (仅当useFlow为1时进行格式限制)
  if (props.checkFile) {
    if (allowedExtensions.value&&allowedExtensions.value.length>0){
      const fileName = file.name.toLowerCase()
      const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1)
      if (!allowedExtensions.value.includes(fileExtension)) {
        message.error('不支持的文件类型！')
        return false
      }
    }
  }
  
  // 1.2 检查文件大小
  if (!(file.size / 1024 / 1024 < props.maxFileSize)) {
    message.error(`文件大小不能超过 ${props.maxFileSize} MB！`)
    return false
  }

  // 2. 增加上传中的文件计数
  uploadingCount.value++
  return true
}
onBeforeMount(()=>{
  console.log("onBeforeMount",props.modelValue)
  if (props.modelValue){
    if (Array.isArray(props.modelValue)){
      const data = props.modelValue as string[]
      urls.push(...data)
      const fs=data.map(f=>{
        return {name:f,url:f}  as UploadUserFile
      })
      fileList.push(...fs)
    }
    if (typeof props.modelValue === 'string'){
      const d= {name:props.modelValue,url:props.modelValue}  as UploadUserFile
      urls.push(props.modelValue)
      fileList.push(d)
    }
  }
})
defineExpose({})
</script>

<template>
  <el-upload
    class="upload-demo"
    :action="uploadUrl"
    v-model:file-list="fileList"
    :http-request="httpRequest"
    :auto-upload="true"
    multiple
    :limit="props.limit"
    :on-error="onUploadError"
    :before-upload="beforeUpload"
  >
    <template #trigger>
      <el-button type="primary" link>选择文件</el-button>
      <div>
        <div> 最大支持{{ maxFileSize }}MB </div>
        <div v-if="useFlow === '1'"> 支持格式: {{ allowedExtensions.join(',') }} </div>
      </div>
    </template>
  </el-upload>
</template>

<style scoped lang="scss"></style>
